package com.itbaizhan.shopping_common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.core.toolkit.ParameterUtils;
import com.itbaizhan.shopping_common.exception.BusException;
import com.itbaizhan.shopping_common.pojo.ShoppingUser;

import java.util.Date;

/**
 * @author spf
 * @date 2024/1/12
 * @time 15:02
 */

// JWT单点登录
public class JWTUtil {
    // 过期时间
    private static final Long EXPIRE_DATE = 1000 * 60 * 24L;
    // 密钥
    private static final String SECRET = "baizhan";
    // 签发者
    private static final String ISSUER = "BAIZHAN";

    /**
     * 签名生成
     *
     * @param shoppingUser 商城用户对象
     * @return 令牌
     */
    public static String sign(ShoppingUser shoppingUser) {
        String token = JWT.create()
                .withIssuer(ISSUER) //签发者
                .withIssuedAt(new Date()) // 签发时间
                .withExpiresAt(new Date(new Date().getTime() + EXPIRE_DATE)) // 过期时间
                .withSubject(shoppingUser.getUsername()) // 保存用户名
                .withClaim("userId", shoppingUser.getId())
                .sign(Algorithm.HMAC256(SECRET)); // 密钥
        return token;
    }

    /**
     * 签名解析，获取用户名
     * @param token 签名字符串
     * @return 用户名
     */
    public static String verify(String token) {
        try {
            String username = JWT.require(Algorithm.HMAC256(SECRET))
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token)
                    .getSubject();
            return username;
        } catch (Exception e) {
            throw new BusException();
        }
    }

    /**
     * 解析签名，获取 用户id
     * @param token 令牌
     * @return 获取用户id
     */
    public static Long getId(String token) {
        try {
            Long userId = JWT.require(Algorithm.HMAC256(SECRET))
                    .withIssuer(ISSUER)
                    .build()
                    .verify(token)
                    .getClaim("userId")
                    .asLong();
            return userId;
        } catch (Exception e) {
            throw new BusException();
        }
    }
}
